﻿
using mozhi.smarterp.Finance.Basedatas;
using mozhi.smarterp.Finance.Basedatas.Events;
using mozhi.smarterp.Finance.Basedatas.Repository;
using mozhi.smarterp.Finance.Querys;
using System.Threading.Tasks;
using Volo.Abp.DependencyInjection;
using Volo.Abp.EventBus.Distributed;
using Volo.Abp.Guids;

namespace mozhi.smarterp.Finance.Basedata.EventHandlers
{
    public class DataAssociationAddEventHandler : IDistributedEventHandler<DataAssociationAddEvent>,
          ITransientDependency
    {
        private IDataAssociationRepository _dataAssociationsRepository;
        private IGuidGenerator _guidGenerator;
        public DataAssociationAddEventHandler(IDataAssociationRepository dataAssociationsRepository, IGuidGenerator guidGenerator)
        {
            _dataAssociationsRepository = dataAssociationsRepository;
            _guidGenerator = guidGenerator;
        }

        public async Task HandleEventAsync(DataAssociationAddEvent eventData)
        {
            //实现等幂性，先查询有没有引用关系，防止插入重复
            var associations = await _dataAssociationsRepository.FindAsync(new DataAssociationQuery() { OccupantId = eventData.OccupantId, OccupiedId = eventData.OccupiedId });

            if (associations.Count > 0)
                return;

            //新增
            var association = new DataAssociation(_guidGenerator.Create(), eventData.OccupantId, eventData.OccupantType, eventData.OccupantTypeName, eventData.OccupantCode, eventData.OccupantName,
                eventData.OccupiedId, eventData.OccupiedType, null, null, null);

            await _dataAssociationsRepository.InsertAsync(association);
        }
    }
}
